import type TiledMap from "tiled-types";
import { loadMap } from "./map";
import { globalScale } from "@/config/static";
import { useCameraStore } from "@/store/cameraStore";

// 获取屏幕宽高
export const getScreenSize = () => {
  // console.log("屏幕物理分辨率:", screen.width, "x", screen.height);
  // console.log("浏览器视口大小:", window.innerWidth, "x", window.innerHeight);

  return {
    width: window.innerWidth,
    height: window.innerHeight,
  };
};

/**
 * 加载图片
 * @param src 图片路径
 * @returns 图片
 */
export const loadImage = async (src: string): Promise<HTMLImageElement> => {
  const image = new Image();
  image.src = src;

  return new Promise<HTMLImageElement>((resolve) => {
    image.onload = () => resolve(image);
  });
};

/**
 * 绘制网格
 * @param ctx 画布上下文
 * @param map 地图数据
 * @param scale 缩放比例
 */
export const drawGrid = (
  ctx: CanvasRenderingContext2D,
  map: TiledMap,
  scale: number
) => {
  ctx.save();
  ctx.strokeStyle = "rgba(0,0,0,0.2)";
  ctx.lineWidth = 1;
  ctx.beginPath();
  const width = map.width * map.tilewidth;
  const height = map.height * map.tileheight;
  // 横线
  for (let y = 0; y <= map.height; y++) {
    ctx.moveTo(0, y * map.tileheight);
    ctx.lineTo(width, y * map.tileheight);
  }
  // 竖线
  for (let x = 0; x <= map.width; x++) {
    ctx.moveTo(x * map.tilewidth, 0);
    ctx.lineTo(x * map.tilewidth, height);
  }
  ctx.stroke();
  ctx.restore();
};

/**
 * 获取单元格位置
 * @param x 鼠标x坐标
 * @param y 鼠标y坐标
 * @param gridSize 网格大小
 * @returns 单元格位置
 */
export const getCellPosition = async (
  mouseX: number,
  mouseY: number
): Promise<{ x: number; y: number }> => {
  const map = await loadMap("/src/assets/maps/baseMap.json");

  // 获取相机偏移量
  const cameraStore = useCameraStore();
  const cameraOffset = cameraStore.cameraOffset;

  const scale = globalScale;

  // 得到游戏世界中的实际坐标
  const worldX = mouseX / scale + cameraOffset.x;
  const worldY = mouseY / scale + cameraOffset.y;

  // 计算网格坐标
  const gridX = Math.floor(worldX / map.tilewidth);
  const gridY = Math.floor(worldY / map.tileheight);

  // 返回网格坐标，要减去相机偏移量
  return {
    x: (gridX * map.tilewidth - cameraOffset.x) * globalScale,
    y: (gridY * map.tileheight - cameraOffset.y) * globalScale,
  };
};

/**
 * 防抖
 * @param fn 函数
 * @param delay 延迟时间
 * @returns 函数
 */
export const debounce = (fn: Function, delay: number) => {
  let timer: number | null = null;
  return function (this: any, ...args: any[]) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = window.setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

/**
 * 根据世界坐标获取网格索引
 * @param worldX 世界X坐标
 * @param worldY 世界Y坐标
 * @param gridSize 网格大小，默认为16
 * @returns 网格索引对象 {x, y}
 */
export function getGridIndex(
  worldX: number,
  worldY: number,
  gridSize: number = 16
) {
  return {
    x: Math.floor(worldX / gridSize),
    y: Math.floor(worldY / gridSize),
  };
}
